﻿/*
 * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
 *
 * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

#include <signal.h>
#include <atomic>
#include <iostream>
#include "Util/logger.h"
#include "Util/TimeTicker.h"
#include "Thread/ThreadPool.h"

using namespace std;
using namespace toolkit;

uint64_t  lastCount = 0, nowCount = 1;
Ticker* ticker;

void Run(atomic_llong &count, ThreadPool *pool)
{
#define NUM_ 1000*10000
//#define NUM_ 10
    if (!ticker)
    {
        InfoL << "ticker:" << ticker;
        return;
    }
	for (int i = 0; i < NUM_;++i) {
		pool->async([&]() {
			InfoL << count;
            InfoL << "===ticker:" << ticker;
			if (++count >= NUM_) {
				InfoL << "执行1000万任务总共耗时:" << ticker->elapsedTime() << "ms";
			}
			});
	}
//	InfoL << "1000万任务入队耗时:" << ticker.elapsedTime() << "ms" << endl;
    lastCount = 0, nowCount = 1;
//	ticker.resetTime();
}

int main() {
    signal(SIGINT,[](int ){
        exit(0);
    });
    //初始化日志系统
    Logger::Instance().add(std::make_shared<ConsoleChannel> ());

    //获取硬件支持并发数
 //   InfoL << thread::hardware_concurrency();
    atomic_llong count(0);
    ThreadPool *pool = new ThreadPool(1,ThreadPool::PRIORITY_HIGHEST, false);
    ticker = new Ticker;

    //此处才开始启动线程
    pool->start();

    std::thread threadObj(Run, std::ref(count), pool);
    threadObj.detach();
    while (true){
        sleep(1);
        nowCount = count.load();
        InfoL << "每秒执行任务数:" << nowCount - lastCount;
        if(nowCount - lastCount == 0){
            break;
        }
        lastCount = nowCount;
    }
    delete ticker;
    delete pool;
    system("pause");
    return 0;
}
